package com.admin.web;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.admin.model.FileMeta;
import com.admin.service.AdminCTSService;
import com.admin.service.AdminChooseService;
import com.admin.service.AdminProjectService;
import com.admin.service.AdminSchoolService;
import com.admin.util.AdminProjectExcelTool;
import com.admin.util.AdminScoreExcelTool;
import com.admin.util.AdminStudentExcelTool;
import com.common.model.AdminUser;
import com.common.model.ClassInfo;
import com.common.model.Project;
import com.common.model.StudentUser;
import com.common.model.TimePlan;

@Controller
@RequestMapping("/admin/choose")
public class AdminChooseWeb {
	@Autowired
	AdminSchoolService schooService;
	@Autowired
	AdminCTSService ctsService;
	@Autowired
	AdminChooseService choService;
	@Autowired
	AdminProjectService prjService;
	/**
	 * 根据条件查询未选题的学生
	 * @param classId 班级id
	 * @param page 页码(从1开始)
	 * @return
	 */
	@RequestMapping("/showUnchooseList/{class_id}/{page}")
	public ModelAndView showUnchooseList(
			@PathVariable("class_id") int classId,
			@PathVariable("page")int page,
			HttpSession session){
		ModelAndView mav=new ModelAndView();
		mav.setViewName("admin/choose/showUnchooseList");
		mav.addObject("colleges", schooService.getAllCollege());
		AdminUser admin=(AdminUser)session.getAttribute("user");
		ClassInfo classInfo=ctsService.getClassByClassId(classId);
		if(classInfo==null){
			if(admin.isSuperAdmin()){
				classInfo=ctsService.getMinClass();
			}else{
				classInfo=ctsService.getMinClassOfCollege(admin.getCollegeId());
			}
		}else{
			if(!admin.isSuperAdmin()&&classInfo.getBranch().getProf().getDepartment().getCollege().getId()!=admin.getCollegeId()){
				classInfo=ctsService.getMinClassOfCollege(admin.getCollegeId());
			}
		}
		classId=classInfo.getId();
		
		
		int studentCount=choService.getUnchooseCountByClassId(classId);
		int totalPage=(int)Math.ceil(studentCount/10.0);
		if(totalPage==0){
			totalPage=1;
		}
		if(page>totalPage){
			page=totalPage;
		}
		mav.addObject("classInfo", classInfo);
		mav.addObject("page", page);
		mav.addObject("unchooseList",choService.getUnchooseListByClassId(classId, page));
		mav.addObject("studentCount",studentCount );
		mav.addObject("totalPage",totalPage);
		mav.addObject("currentMenu", "showUnchooseList");
		return mav;
	}
	/**
	 * 查找某个学生可选的题目列表
	 * @param stuId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getAvailableProjectOfStudent/{stu_id}")
	public ArrayList<Project> getAvailableProjectOfStudent(@PathVariable("stu_id")int stuId){
		return choService.getAvailableProjectOfStudent(stuId);
	}
	/**
	 * 手动选题
	 * @param prjId
	 * @param stuId
	 * @return -1无权限 -2无题目 -3 无学生 -4 题目已选 -5 未审核 -6专业方向不适合 -7已选题目 -8其他错误
	 */
	@ResponseBody
	@RequestMapping("/setChooseManual/{prj_id}/{stu_id}")
	public int setChooseManual(@PathVariable("prj_id")int prjId,@PathVariable("stu_id")int stuId,HttpSession session){
		AdminUser admin=(AdminUser)session.getAttribute("user");
		StudentUser stu=ctsService.getStudentByStuId(stuId);
		if(stu==null){
			return -3;
		}
		int stuClgId=stu.getClassInfo().getBranch().getProf().getDepartment().getCollege().getId();
		if(!(admin.isSuperAdmin()||admin.getCollegeId()==stuClgId)){
			return -1;
		}
		Project prj=prjService.getProjectByPrjId(prjId);
		if(prj==null){
			return -2;
		}
		int prjClgId=prj.getTeacher().getDepartment().getCollege().getId();
		if(!(admin.isSuperAdmin()||admin.getCollegeId()==prjClgId)){
			return -1;
		}
		int result=choService.setChooseManual(prjId, stuId);
		if(result==0){
			return 0;
		}
		return result-1;
	}
	@RequestMapping("/unchooseList.xlsx")
	public void getUnchooseList2007(HttpServletResponse response){
		ArrayList<StudentUser> stuList=choService.getUnchooseListByAll();
		try {
			AdminStudentExcelTool.exportTo2007(stuList).write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}	
	@RequestMapping("/unchooseList.xls")
	public void getUnchooseList2003(HttpServletResponse response){
		ArrayList<StudentUser> stuList=choService.getUnchooseListByAll();
		try {
			AdminStudentExcelTool.exportTo2003(stuList).write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("/autoChoose")
	public ModelAndView autoChoose(HttpSession session){
		ModelAndView mav=new ModelAndView();
		AdminUser admin=(AdminUser)session.getAttribute("user");
		mav.addAllObjects( choService.autoChooseProject(admin));
		mav.setViewName("admin/choose/autoChooseReport");
		mav.addObject("currentMenu", "showUnchooseList");
		return mav;
	}
	@RequestMapping("/showChooseHelper/{clg_id}/{page}")
	public ModelAndView showChooseHelper(@PathVariable("clg_id")int clgId,@PathVariable("page")int page,HttpSession session){
		ModelAndView mav=new ModelAndView();
		AdminUser admin=(AdminUser)session.getAttribute("user");
		if(!admin.isSuperAdmin()){
			clgId=admin.getCollegeId();
		}else{
			int minClgId=schooService.getMinCollegeId();
			if(clgId<minClgId){
				clgId=minClgId;
			}
		}
		if(choService.getIsChooseByPrj(clgId)){
			mav.setViewName("admin/choose/showChooseByPrj");
			int prjCount=choService.getUnchooseProjectCount(clgId);
			int totalPage=(int)Math.ceil(prjCount/10.0);
			if(totalPage==0){
				totalPage=1;
			}
			if(page>totalPage){
				page=totalPage;
			}
			mav.addObject("colleges", schooService.getAllCollege());
			mav.addObject("totalPage", totalPage);
			mav.addObject("page", page);
			mav.addObject("clgId", clgId);
			mav.addObject("prjCount", prjCount);
			mav.addObject("prjList", choService.getUnchooseProject(clgId, page));
		}else{
			mav.setViewName("admin/choose/showChooseByTea");
			int teaCount=choService.getUnFinishTeacherCount(clgId);
			int totalPage=(int)Math.ceil(teaCount/10.0);
			if(totalPage==0){
				totalPage=1;
			}
			if(page>totalPage){
				page=totalPage;
			}
			mav.addObject("colleges", schooService.getAllCollege());
			mav.addObject("totalPage", totalPage);
			mav.addObject("page", page);
			mav.addObject("clgId", clgId);
			mav.addObject("teaCount", teaCount);
			mav.addObject("teaList", choService.getUnFinishTeacher(clgId, page));
		}
		mav.addObject("currentMenu", "showChoose");
		return mav;
	}
	@RequestMapping("/set/{clg_id}")
	public ModelAndView showChooseSet(@PathVariable("clg_id")int clgId,HttpSession session){
		ModelAndView mav=new ModelAndView();
		AdminUser admin=(AdminUser)session.getAttribute("user");
		if(!admin.isSuperAdmin()){
			clgId=admin.getCollegeId();
		}else{
			int minClgId=schooService.getMinCollegeId();
			if(clgId<minClgId){
				clgId=minClgId;
			}
		}
		mav.addObject("clgId", clgId);
		mav.addObject("colleges", schooService.getAllCollege());
		mav.addObject("set", choService.getChooseSetOfCollege(clgId));
		mav.setViewName("admin/choose/showChooseSet");
		mav.addObject("currentMenu", "showChooseSet");
		return  mav;
	}
	/**
	 * 
	 * @param clgId
	 * @param studentChooseTimeStart
	 * @param studentChooseTimeEnd
	 * @param teacherEditTimeStart
	 * @param teacherEditTimeEnd
	 * @param teacherUploadTimeStart
	 * @param teacherUploadTimeEnd
	 * @param teacherChooseTimeStart
	 * @param teacherChooseEachTimeLength
	 * @param middleCheckTimeStart
	 * @param middleCheckTimeEnd
	 * @param finalCheckTimeStart
	 * @param finalCheckTimeEnd
	 * @param totalLevelCount
	 * @param chooseByProject
	 * @param session
	 * @return -1无权限 -2格式错误 -3学生选题时间错误,-4 教师编辑时间错误 -5附件提交时间错误,-6中期检查时间错误 -7 最终检查时间错误
	 */
	@ResponseBody
	@RequestMapping("/updateChooseSet")
	public int updateChooseSet(
			Integer clgId,
			String studentChooseTimeStart,
			String studentChooseTimeEnd,
			String teacherEditTimeStart,
			String teacherEditTimeEnd,
			String teacherUploadTimeStart,
			String teacherUploadTimeEnd,
			String teacherChooseTimeStart,
			Integer teacherChooseEachTimeLength,
			String middleCheckTimeStart,
			String middleCheckTimeEnd,
			String finalCheckTimeStart,
			String finalCheckTimeEnd,
			Integer totalLevelCount,
			Integer chooseByProject,
			HttpSession session
			){
		AdminUser admin=(AdminUser)session.getAttribute("user");
		if(!(admin.isSuperAdmin()||admin.getCollegeId()==clgId)){
			return -1;
		}
		TimePlan plan=new TimePlan();
		plan.setCollegeId(clgId);
		try{
			plan.setStudentChooseTimeStart(Timestamp.valueOf(studentChooseTimeStart));
			plan.setStudentChooseTimeEnd(Timestamp.valueOf(studentChooseTimeEnd));
			plan.setTeacherEditTimeStart(Timestamp.valueOf(teacherEditTimeStart));
			plan.setTeacherEditTimeEnd(Timestamp.valueOf(teacherEditTimeEnd));
			plan.setTeacherUploadTimeStart(Timestamp.valueOf(teacherUploadTimeStart));
			plan.setTeacherUploadTimeEnd(Timestamp.valueOf(teacherUploadTimeEnd));
			plan.setTeacherChooseTimeStart(Timestamp.valueOf(teacherChooseTimeStart));
			plan.setTeacherChooseEachTimeLength(teacherChooseEachTimeLength);
			plan.setMiddleCheckTimeStart(Timestamp.valueOf(middleCheckTimeStart));
			plan.setMiddleCheckTimeEnd(Timestamp.valueOf(middleCheckTimeEnd));
			plan.setFinalCheckTimeStart(Timestamp.valueOf(finalCheckTimeStart));
			plan.setFinalCheckTimeEnd(Timestamp.valueOf(finalCheckTimeEnd));
			plan.setTotalLevelCount(totalLevelCount);
			plan.setChooseByProject(chooseByProject==1);
		}catch(Exception e){
			return -2;
		}
		if(plan.getStudentChooseTimeEnd().before(plan.getStudentChooseTimeStart())){
			return -3;
		}
		if(plan.getTeacherEditTimeEnd().before(plan.getTeacherEditTimeStart())){
			return -4;
		}
		if(plan.getTeacherUploadTimeEnd().before(plan.getTeacherUploadTimeStart())){
			return -5;
		}
		if(plan.getMiddleCheckTimeEnd().before(plan.getMiddleCheckTimeStart())){
			return -6;
		}
		if(plan.getFinalCheckTimeEnd().before(plan.getFinalCheckTimeStart())){
			return -7;
		}
		if(plan.getTeacherChooseTimeStart().before(plan.getStudentChooseTimeEnd())){
			return -8;
		}
		if(plan.getFinalCheckTimeStart().before(plan.getMiddleCheckTimeEnd())){
			return -9;
		}
		if(plan.getTeacherChooseEachTimeLength()<1||plan.getTotalLevelCount()<1){
			return -10;
		}
		choService.updateTimeplan(plan);
		return 0;
	}
	
	/**
	 * 根据条件查询成绩列表
	 * @param clgId 学院id
	 * @param page 页码(从1开始)
	 * @return
	 */
	@RequestMapping("/showScoreList/{clg_id}/{page}")
	public ModelAndView showScoreList(
			@PathVariable("clg_id") int clgId,
			@PathVariable("page")int page,
			HttpSession session){
		ModelAndView mav=new ModelAndView();
		mav.setViewName("admin/choose/showScoreList");
		mav.addObject("colleges", schooService.getAllCollege());
		AdminUser admin=(AdminUser)session.getAttribute("user");
		if(admin.isSuperAdmin()){
			int minClgId=schooService.getMinCollegeId();
			if(clgId<minClgId){
				clgId=minClgId;
			}
		}else{
			clgId=admin.getCollegeId();
		}
		
		int scoreCount=choService.getScoreCountByCollege(clgId);
		int totalPage=(int)Math.ceil(scoreCount/10.0);
		if(totalPage==0){
			totalPage=1;
		}
		if(page>totalPage){
			page=totalPage;
		}
		mav.addObject("clgId", clgId);
		mav.addObject("page", page);
		mav.addObject("scoreList",choService.getScoreByCollege(clgId,  page));
		mav.addObject("scoreCount",scoreCount );
		mav.addObject("totalPage",totalPage);
		mav.addObject("currentMenu", "showScoreList");
		return mav;
	}
	/**
	 * 由excel导入成绩
	 * @param excel
	 * @param session
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/insertScoreByExcel")
	public ArrayList<FileMeta> insertScoreByExcel(MultipartFile excel,HttpSession session) throws IOException{
		FileMeta file=new FileMeta();
		file.setFileName(excel.getOriginalFilename().toLowerCase());
		file.setFileSize(excel.getSize()/1024.0+"kb");
		file.setFileType(excel.getContentType());
		file.setInputStresm(excel.getInputStream());
		choService.insertScoreByExcel(file, session);
		ArrayList<FileMeta> arr=new ArrayList<FileMeta>();
		arr.add(file);
		return arr;
	}
	@RequestMapping("/showInsertReport")
	public ModelAndView showInsertByExcelResult( HttpSession session){
		ModelAndView mav=new ModelAndView();
		if(session.getAttribute("scoreExcelReadResult")==null){
			mav.setViewName("redirect:showScoreList/1/1");
			return mav;
		}
		mav.setViewName("admin/choose/importScoreReport");
		mav.addObject("report", session.getAttribute("scoreExcelReadResult"));
		mav.addObject("successCount", session.getAttribute("scoreExcelReadSuccessCount"));
		session.removeAttribute("scoreExcelReadResult");
		session.removeAttribute("scoreExcelReadSuccessCount");
		mav.addObject("currentMenu", "showScoreList");
		return mav;
	}
	@RequestMapping("/{clg_id}/scoretList.xlsx")
	public void getPrjList2007(@PathVariable("clg_id") int clgId,HttpSession session,HttpServletResponse response){
		AdminUser admin=(AdminUser)session.getAttribute("user");
		if(admin.isSuperAdmin()){
			int minClgId=schooService.getMinCollegeId();
			if(clgId<minClgId){
				clgId=minClgId;
			}
		}else{
			clgId=admin.getCollegeId();
		}
		try {
			AdminScoreExcelTool.exportTo2007(choService.getScoreByCollegeNoPage(clgId)).write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}	
	@RequestMapping("/{clg_id}/scoretList.xls")
	public void getPrjList2003(@PathVariable("clg_id") int clgId,HttpSession session,HttpServletResponse response){
		AdminUser admin=(AdminUser)session.getAttribute("user");
		if(admin.isSuperAdmin()){
			int minClgId=schooService.getMinCollegeId();
			if(clgId<minClgId){
				clgId=minClgId;
			}
		}else{
			clgId=admin.getCollegeId();
		}
		try {
			AdminScoreExcelTool.exportTo2003(choService.getScoreByCollegeNoPage(clgId)).write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}	
}
